package com.dmcb.trade.business.crawlers.article;

import com.dmcb.common.business.utils.DateUtil;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.entities.Article;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 大学生在线文章解析
 * Created by Administrator on 2016/6/29.
 */
@Service
public class DaXueShengZaiXianParser extends BaseParser {

    /**
     * 网站URL网址
     *
     * @return 链接
     */
    @Override
    protected String url() {
        return CrawlConstant.DAXUESHENGZAIXIAN_URL;
    }

    /**
     * 获取标题选择器
     *
     * @return 标题选择器
     */
    @Override
    protected String titleSelect() {
        return "div.storyTitle b";
    }

    /**
     * 获取日期选择器
     *
     * @return 发布日期选择器
     */
    @Override
    protected String dateSelect() {
        return "div.storyTime";
    }

    /**
     * 获取正文内容选择器
     *
     * @return 正文内容选择器
     */
    @Override
    protected String bodySelect() {
        return "div.articleContent";
    }

    /**
     * 获取封面选择器
     *
     * @return 封面选择器
     */
    @Override
    protected String coverSelect() {
        return "div.articleContent>p img[src]";
    }


    /**
     * 设置发布时间
     *
     * @param doc     网页
     * @param article 文章
     */
    @Override
    protected void setPostDate(Document doc, Article article) {
        Element element = doc.select(dateSelect()).first();
        if (element != null) {
            String date = element.text();
            Date time = null;
            date = date.trim();
            date = date.replace(".", "-").replace("年", "-").replace("月", "-").replace("日 ", " ").replace("日", " ").replace("/", "-");
            date = DateUtil.matchDate(date);
            try {
                SimpleDateFormat sdf;
                date = DateUtil.format(new Date(), "yyyy-").substring(0,2) + date;
                if (date.contains(":")) {
                    if (date.indexOf(":") == date.lastIndexOf(":")) {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    } else {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                } else {
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                }
                time  =  sdf.parse(date);
            } catch (Exception e) {
                time = new Date();
            }
            if (date != null) {
                article.setPostTime(time);
            }
        }
    }

    @Override
    protected String platform() {
        return "大学生在线网";
    }
}

